package com.cuitrip.app.rong;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cuitrip.apiservice.MessageBusiness;
import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.app.MainApplication;
import com.cuitrip.app.base.CtException;
import com.cuitrip.app.base.CtFetchCallback;
import com.cuitrip.app.base.ImageActivity;
import com.cuitrip.app.rong.model.RongMessageModel;
import com.cuitrip.business.conversation.rong.RongMessageProxy;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.location.map.GaoDeMapActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.order.detail.OrderFormActivity;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.im.CtParam;
import com.cuitrip.im.model.CTInformationNotificationMessage;
import com.cuitrip.im.proxy.CtRongInfoProxy;
import com.cuitrip.service.R;
import com.cuitrip.util.PlatformUtil;
import com.lab.logtrack.AppLog;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.Utils;
import com.sea_monster.exception.BaseException;
import com.sea_monster.network.AbstractHttpRequest;
import com.sea_monster.network.ApiCallback;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import io.rong.imkit.RongIM;
import io.rong.imkit.model.GroupUserInfo;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.InformationNotificationMessage;
import io.rong.message.LocationMessage;
import io.rong.message.RichContentMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;
import io.rong.notification.PushNotificationMessage;

/**
 * Created by baziii on 15/8/11.
 */
public final class RongCloudEvent implements RongIMClient.OnReceiveMessageListener, RongIM.OnSendMessageListener,
        RongIM.UserInfoProvider, RongIM.GroupInfoProvider, RongIM.ConversationBehaviorListener,
        RongIMClient.ConnectionStatusListener, RongIM.LocationProvider, RongIMClient.OnReceivePushMessageListener, RongIM.ConversationListBehaviorListener,
        ApiCallback, Handler.Callback, RongIM.GroupUserInfoProvider {
    public static final String TAG = "RongCloudEvent";

    public static final int DEFAULT_CHECK_MODE_NOTIFCATION_ID = 2;
    public static final int DEFAULT_ERROR_NOTIFCATION_ID = 3;

    public static String currentToken;
    public static String ORDER_ID;
    public static String USER_ID;
    public static String RECEIVER_ID;
    public static String SERVICE_ID;

    //query for userinfo  from api && local  ??
    public static String TARGET_ID;
    private static RongIMClient.ErrorCode mErrorCode;
    private static RongCloudEvent sRongCloudEvent;

    private RongCloudEvent() {

    }

    public static RongCloudEvent getInstance() {
        if (sRongCloudEvent == null) {
            synchronized (RongCloudEvent.class) {
                if (sRongCloudEvent == null) {
                    sRongCloudEvent = new RongCloudEvent();
                }
            }
        }
        return sRongCloudEvent;
    }

    public static void DisConnectRong() {
        if (RongIM.getInstance() != null && (RongCloudEvent.getInstance().isConnected()
                || RongCloudEvent.getInstance().isConnecting())) {
            LogHelper.e("ron", "logout");
            RongIM.getInstance().logout();
        }
    }

    public static void ConnectRongForce() {
        ConnectRong(true);
    }

    public static void ConnectRong(boolean forceExit) {
        try {
            if (!LoginInstance.isLogin()) {
                LogHelper.e(TAG, " notlogin");
                return;
            }
            final CtUserInfo ctUserInfo = LoginInstance.getInstance().getUserInfo();
            if (ctUserInfo == null || TextUtils.isEmpty(ctUserInfo.getUid())) {
                LogHelper.e(TAG, " userinfo null");
                return;
            }
            if (TextUtils.isEmpty(ctUserInfo.getRongyunToken())) {
                LogHelper.e(TAG, "rongyun roken null");
                if (forceExit) {
                    MainApplication.getInstance().logOutWithError();
                }
                return;
            }

            if (currentToken != null && currentToken.equals(ctUserInfo.getRongyunToken())) {
                //状态池维护 很蛋疼，还是得抽出来
                if (RongCloudEvent.getInstance().isConnecting()) {
                    LogHelper.e(TAG, " isConnecting");
                    return;

                }
                if (RongCloudEvent.getInstance().isConnected()) {
                    LogHelper.e(TAG, " already");
                    return;
                }
            }
            //if connected

            final String token = ctUserInfo.getRongyunToken();
            LogHelper.e(TAG, "rongyun roken is : " + token);
            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                @Override
                public void onSuccess(String userId) {
                    currentToken = token;
                    mErrorCode = null;
                    LogHelper.e(TAG, "ron suc" + userId);
                    UserInfo userInfo = new UserInfo(ctUserInfo.getUid(), ctUserInfo.getNick(), Uri.parse(ctUserInfo.getHeadPic() == null ? "" : ctUserInfo.getHeadPic()));
                    RongIM.getInstance().setCurrentUserInfo(userInfo);
                    RongIM.getInstance().setMessageAttachedUserInfo(true);
    /* 连接成功 */
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {
                    LogHelper.e(TAG, "ron failed " + e);
                    mErrorCode = e;
    /* 连接失败，注意并不需要您做重连 */
                }

                @Override
                public void onTokenIncorrect() {
                    LogHelper.e(TAG, "ron token error");
                    try {
                        MainApplication.getInstance().logOutWithError();
                    } catch (Exception e) {
                    }
                }

            });
        } catch (Exception e) {
            MessageUtils.showToast(R.string.feedback_no_internet_1);
        }
    }

    public static void forceConnect() {
        try {
            if (!LoginInstance.isLogin()) {
                LogHelper.e(TAG, " notlogin");
                return;
            }
            final CtUserInfo ctUserInfo = LoginInstance.getInstance().getUserInfo();
            if (ctUserInfo == null || TextUtils.isEmpty(ctUserInfo.getUid())) {
                LogHelper.e(TAG, " userinfo null");
                return;
            }
            if (TextUtils.isEmpty(ctUserInfo.getRongyunToken())) {
                LogHelper.e(TAG, "rongyun roken null");
            }

            final String token = ctUserInfo.getRongyunToken();
            LogHelper.e(TAG, "rongyun roken is : " + token);
            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                @Override
                public void onSuccess(String userId) {
                    currentToken = token;
                    UserInfo userInfo = new UserInfo(ctUserInfo.getUid(), ctUserInfo.getNick(), Uri.parse(ctUserInfo.getHeadPic() == null ? "" : ctUserInfo.getHeadPic()));
                    RongIM.getInstance().setCurrentUserInfo(userInfo);
                    RongIM.getInstance().setMessageAttachedUserInfo(true);
                    LogHelper.e(TAG, "ron suc" + userId);
                    mErrorCode = null;
    /* 连接成功 */
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {
                    LogHelper.e(TAG, "ron failed " + e);
                    mErrorCode = e;
    /* 连接失败，注意并不需要您做重连 */
                }

                @Override
                public void onTokenIncorrect() {
                    LogHelper.e(TAG, "ron token error");
                    try {
                        MainApplication.getInstance().logOutWithError();
                    } catch (Exception e) {
                    }
                }

            });
        } catch (Exception e) {
            MessageUtils.showToast(R.string.feedback_no_internet_1);
        }
    }

    public static String getMessageContent(MessageContent messageContent) {

        String content = "";
        if (messageContent instanceof TextMessage) {//文本消息
            TextMessage textMessage = (TextMessage) messageContent;
            content = textMessage.getContent();
        } else if (messageContent instanceof ImageMessage) {//图片消息
            content = PlatformUtil.getInstance().getString(R.string.chat_msg_type_image);
        } else if (messageContent instanceof VoiceMessage) {//语音消息
            content = PlatformUtil.getInstance().getString(R.string.chat_msg_type_voice);
        } else if (messageContent instanceof RichContentMessage) {//图文消息
            content = PlatformUtil.getInstance().getString(R.string.chat_msg_type_image_text);
        } else if (messageContent instanceof LocationMessage) {//位置信息
            content = PlatformUtil.getInstance().getString(R.string.chat_msg_type_location);
        } else if (messageContent instanceof InformationNotificationMessage) {//小灰条消息
            InformationNotificationMessage informationNotificationMessage = (InformationNotificationMessage) messageContent;
            LogHelper.e(TAG, "onReceived-informationNotificationMessage:" + informationNotificationMessage.getMessage());
            content = PlatformUtil.getInstance().getString(R.string.chat_msg_type_notice);
        } else if (messageContent instanceof CTInformationNotificationMessage) {
            //处理融云订单消息去刷新订单
            CTInformationNotificationMessage informationNotificationMessage = (CTInformationNotificationMessage) messageContent;
            CtParam param = CtParam.parseObject(informationNotificationMessage.getExtra());
            if (param != null && CtParam.ORDER_KEY.equals(param.cuitrip) && CtRongInfoProxy.RONG_MSG_RECEIVE_OPEN) {
                AppCoreRuntime.context.sendBroadcast(new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));
            }
        } else {
            if (messageContent == null) {
                content = PlatformUtil.getInstance().getString(R.string.chat_msg_type_notice);
            } else {
                content = null;
            }
        }
        return content;
    }

    public static void onConversationStart(String orderid, String receiverId,
                                           String uid,
                                           String serviceid, String targetId) {
        LogHelper.e(TAG,
                TextUtils.join("|",
                        new String[]{" onConversationStart", orderid, receiverId, uid, serviceid, targetId}
                ));
        if (TextUtils.isEmpty(orderid)
                || TextUtils.isEmpty(receiverId)
                || TextUtils.isEmpty(uid)
                || TextUtils.isEmpty(serviceid)
                || TextUtils.isEmpty(targetId)
                ) {
            return;
        }
        ORDER_ID = orderid;
        USER_ID = uid;
        RECEIVER_ID = receiverId;
        SERVICE_ID = serviceid;
        TARGET_ID = targetId;
    }

    private static boolean isNotEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    /**
     * 过滤emoji 或者 其他非文字类型的字符
     *
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {
        int len = source.length();

        StringBuilder buf = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (isNotEmojiCharacter(codePoint)) {
                buf.append(codePoint);
            } else {
                buf.append("[emoji]");
            }
        }
        LogHelper.e(TAG, " filtereEmoji " + source + " >>" + buf.toString());
        return buf.toString();
    }

    public static Pair<Integer, String> getMessageLoadToService(MessageContent messageContent) {

        String content = "";
        int contentType = 1;
        if (messageContent instanceof TextMessage) {//文本消息
            TextMessage textMessage = (TextMessage) messageContent;
            content = filterEmoji(textMessage.getContent());
            contentType = RongMessageModel.TEXT_MSG;
        } else if (messageContent instanceof LocationMessage) {
            content = "CHAT_MSG_TYPE_LOCATION";
            contentType = RongMessageModel.LOCATION_MSG;
        } else if (messageContent instanceof VoiceMessage) {//
            content = "CHAT_MSG_TYPE_VOICE";
            contentType = RongMessageModel.VOICE_MSG;
        } else if (messageContent instanceof ImageMessage) {//图片消息
            content = "CHAT_MSG_TYPE_LOCATION";
            contentType = RongMessageModel.IMAGE_MSG;
        } else if (messageContent instanceof RichContentMessage) {
            content = "CHAT_MSG_TYPE_IMAGE_TEXT";
            contentType = RongMessageModel.IMAGE_TEXT_MSG;
        } else if (messageContent instanceof CTInformationNotificationMessage) {
            content = "CHAT_MSG_TYPE_NOTICE";
            contentType = RongMessageModel.NOTICE_MSG;
        } else {
            content = "CHAT_MSG_TYPE_NOT_SUPPORT";
            contentType = RongMessageModel.NOT_SUPPORT_MSG;
        }
        return new Pair(contentType, content);
    }

    public static String getMessageExtra(MessageContent messageContent) {
        String extra = "";
        if (messageContent instanceof TextMessage) {//文本消息
            TextMessage textMessage = (TextMessage) messageContent;
            extra = textMessage.getExtra();
        } else if (messageContent instanceof LocationMessage) {//
            LocationMessage location = (LocationMessage) messageContent;
            extra = location.getExtra();
        } else if (messageContent instanceof VoiceMessage) {//
            VoiceMessage voiceMessage = (VoiceMessage) messageContent;
            extra = voiceMessage.getExtra();
        } else if (messageContent instanceof ImageMessage) {//图片消息
            ImageMessage imageMessage = (ImageMessage) messageContent;
            extra = imageMessage.getExtra();
        }
        return extra;
    }

    public static String setMessageExtra(MessageContent messageContent, String extra) {
        if (messageContent instanceof TextMessage) {//文本消息
            TextMessage textMessage = (TextMessage) messageContent;
            textMessage.setExtra(extra);
        } else if (messageContent instanceof LocationMessage) {//
            LocationMessage location = (LocationMessage) messageContent;
            location.setExtra(extra);
        } else if (messageContent instanceof VoiceMessage) {//
            VoiceMessage voiceMessage = (VoiceMessage) messageContent;
            voiceMessage.setExtra(extra);
        } else if (messageContent instanceof ImageMessage) {//图片消息
            ImageMessage imageMessage = (ImageMessage) messageContent;
            imageMessage.setExtra(extra);
        }
        return extra;
    }

    public boolean isConnected() {
        return (RongIM.getInstance() != null && RongIM.getInstance().getRongIMClient() != null
                && RongIM.getInstance().getRongIMClient().getCurrentConnectionStatus().equals(ConnectionStatus.CONNECTED));
    }

    public boolean isConnecting() {
        return (RongIM.getInstance() != null && RongIM.getInstance().getRongIMClient() != null
                && RongIM.getInstance().getRongIMClient().getCurrentConnectionStatus().equals(ConnectionStatus.CONNECTING));
    }

    public void startConversation(String title, List<String> userIds, final String oid) {

        startConversation(title, userIds, oid, null);
    }

    public void startConversation(String title, List<String> userIds, final String oid, final CtFetchCallback<String> callback) {
        if (isConnecting() || isConnected()) {
            RongIM.getInstance().getRongIMClient().createDiscussion(title, userIds, new RongIMClient.CreateDiscussionCallback() {
                @Override
                public void onSuccess(final String s) {
                    ApiProxy updateOrderProxy = new ApiProxy(new IProxyCallback() {
                        @Override
                        public boolean onProxyResult(ProxyResult<?> result) {
                            CtApiResponse response = (CtApiResponse) result.getData();
                            if (response.isResponseNormal()) {
                                if (callback != null) {
                                    callback.onSuc(s);
                                }
                            } else {
                                if (callback != null) {
                                    String msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
                                    if (!TextUtils.isEmpty(response.msg)) {
                                        msg = response.msg;
                                    }
                                    callback.onFailed(new CtException(msg));
                                }
                            }
                            return false;
                        }
                    });
                    OrderBusiness.updateOrderConversation(updateOrderProxy, oid, s);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    mErrorCode = errorCode;
                    if (callback != null) {
                        String msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
                        if (!TextUtils.isEmpty(errorCode.getMessage())) {
                            msg = errorCode.getMessage();
                        }
                        callback.onFailed(new CtException(msg));
                    }
                    if (RongIMClient.ErrorCode.IPC_DISCONNECT.equals(errorCode)
                            || RongIMClient.ErrorCode.RC_NET_UNAVAILABLE.equals(errorCode)
                            || RongIMClient.ErrorCode.RC_SOCKET_DISCONNECTED.equals(errorCode)) {
                        forceConnect();
                    }
                }
            });
        } else {
            LogHelper.e("start", " not connected");
        }
    }

    public void sendMessage(Conversation.ConversationType type, String targetId, MessageContent content, String pushContent, String pushData, RongIMClient.SendMessageCallback callback) {
        if (isConnecting() || isConnected()) {
            if (content instanceof CTInformationNotificationMessage) {
                CTInformationNotificationMessage ctInformationNotificationMessage = (CTInformationNotificationMessage) content;
                AppLog.e("send push message ==" + ctInformationNotificationMessage.getContent());
            }
            try {
                RongIM.getInstance().getRongIMClient().sendMessage(type, targetId, content, pushContent, pushData, callback);
            } catch (Exception e) {
                AppLog.e(e.getMessage());
            }
        } else {
            LogHelper.e("start", " not connected");
        }
    }

    @Override
    public UserInfo getUserInfo(final String userId) {
        LogHelper.e("UserInfoProvider", "search uid :" + userId);
        Uri uri = Uri.parse("http://mmbiz.qpic.cn/mmbiz/CCOz0VqjicmxJpUWy6iaibsJ0FcIGaHDLo0TqBHVzyEJOmeaia8mW6jmBnsUrfSJNyd7vAf4sgc9U7ZJ4ydEicNpvZA/0?wx_fmt=gif&wxfrom=5&wx_lazy=1");
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        final List<UserInfo> userInfoList = new ArrayList<>();
        try {
            if (LoginInstance.isLogin()) {
                ApiProxy userInfoProxy = new ApiProxy(new IProxyCallback() {
                    @Override
                    public boolean onProxyResult(ProxyResult<?> result) {
                        CtApiResponse response = (CtApiResponse) result.getData();
                        if (response.isResponseNormal()) {
                            if (response.result instanceof CtUserInfo) {
                                CtUserInfo temp = ((CtUserInfo) response.result);
                                userInfoList.add(new UserInfo(userId, temp.getNick(), Uri.parse(temp.getHeadPic())));
                            }
                            countDownLatch.countDown();
                        } else {
                            countDownLatch.countDown();
                        }
                        return false;
                    }
                });
                userInfoProxy.setShouldResponseOnUiThread(false);
                UserBusiness.getUserInfo(userInfoProxy, userId);
                countDownLatch.await();
            }
        } catch (Exception e) {
            LogHelper.e("UserInfoProvider", "search error " + e.getMessage());
            e.printStackTrace();
        }
        if (userInfoList.size() > 0) {
            LogHelper.e("UserInfoProvider", "search name : " + userInfoList.get(0).getName());
            return userInfoList.get(0);
        }
        LogHelper.e("UserInfoProvider", "search name : null");
        UserInfo empty = new UserInfo(userId, PlatformUtil.getInstance().getString(R.string.feedback_loading), uri);
        return empty;
    }

    @Override
    public boolean onReceived(Message message, int left) {
        LogHelper.e(TAG, "on receive message" + message.getTargetId());
        if (!LoginInstance.isLogin()) {
            return true;
        }
        if (OrderFormActivity.CURRENT_TARGET == null || !OrderFormActivity.CURRENT_TARGET.equals(message.getTargetId())) {
            LogHelper.e(TAG, "on receive message query");
            try {
                CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                if (message.getSenderUserId().equals(userInfo.getUid())) {
                    return true;
                }
                String content = getMessageContent(message.getContent());
                if (!TextUtils.isEmpty(content)) {
                    boolean silence = left > 1;
                    queryForInfo(MainApplication.getInstance(), message.getTargetId(), content, userInfo, false, silence);
                } else {
                    LogHelper.e(TAG, " seems should not see " + message.getObjectName() + "|" + message.toString());
                }
            } catch (Exception e) {
                LogHelper.e(TAG, " error " + e.getMessage());
            }
        }
        return true;

    }

    public void queryForInfo(final Context context, final String targetId, final String content, final CtUserInfo me, boolean async, final boolean silence) {
        LogHelper.e("queryForInfo target ", "" + targetId);
        ApiProxy apiProxy = new ApiProxy(new IProxyCallback() {
            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                CtApiResponse ctApiResponse = (CtApiResponse) result.getData();
                if (ctApiResponse.isResponseNormal()) {
                    if (ctApiResponse.result instanceof OrderItem) {
                        OrderItem orderItem = (OrderItem) ctApiResponse.result;
                        try {

                            if ((me.isTravel() && me.getUid().equals(orderItem.getTravellerId()))
                                    || ((!me.isTravel()) && me.getUid().equals(orderItem.getInsiderId()))) {
                                String title = "";


                                String contentLittle = String.format(content, "");
                                if (!TextUtils.isEmpty(orderItem.getUserNick())) {
                                    title = orderItem.getUserNick();
                                    if (!TextUtils.isEmpty(title)) {
                                        contentLittle = String.format(content, title);
                                    }
                                }

                                AppLog.d("==message receive===" + RongMessageProxy.NEW_MESSAGE_RECEIVED);

                                context.sendBroadcast(
                                        new Intent(RongMessageProxy.NEW_MESSAGE_RECEIVED));
                                String textContent = String.format(content, "");
                                buildNotification(targetId.hashCode(),
                                        orderItem.getUserNick(), textContent, contentLittle, orderItem.getOid(), false, silence);
                                return true;
                            }
                            boolean isTravel = LoginInstance.getInstance().getUserInfo().isTravel();
                            int textRes = isTravel ? R.string.chat_msg_role_confirm_ft : R.string.chat_msg_role_confirm_fi;
                            buildNotification(DEFAULT_CHECK_MODE_NOTIFCATION_ID, context.getString(textRes), content, context.getString(textRes), orderItem.getOid(), true, silence);

                        } catch (Exception e) {
                            buildNotification(DEFAULT_ERROR_NOTIFCATION_ID, context.getString(R.string.chat_msg_type_not_support) + e.getMessage(), content, context.getString(R.string.chat_msg_type_not_support), null, false, silence);
                        }

                    }

                } else {
                    buildNotification(DEFAULT_ERROR_NOTIFCATION_ID, context.getString(R.string.chat_msg_type_not_support), content, context.getString(R.string.chat_msg_type_not_support), null, false, silence);
                }

                return false;
            }
        });
        OrderBusiness.getOrderByRongTargetId(apiProxy, targetId, async);
    }

    public void buildNotification(int id, String content, String title, String contentLittle, String oid, boolean changeRole, boolean silence) {
        LogHelper.e(TAG, TextUtils.join(" | ", new String[]{String.valueOf(id), content, title, contentLittle, oid}));
        //定义NotificationManager
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) MainApplication.getInstance().getSystemService(ns);
        //定义通知栏展现的内容信息
        int icon = R.drawable.ct_icon;
        long when = System.currentTimeMillis();

        Notification.Builder builder = new Notification.Builder(MainApplication.getInstance());
        builder.setSmallIcon(icon);
        builder.setTicker(contentLittle);
        builder.setWhen(when);

        //定义下拉通知栏时要展现的内容信息
        CharSequence contentTitle = title;
        CharSequence contentText = content;
        Intent notificationIntent = new Intent(MainApplication.getInstance(), IndexActivity.class);
        if (!TextUtils.isEmpty(oid)) {
            notificationIntent = OrderFormActivity.getStartConversationIntent(MainApplication.getInstance(), oid);
        }
        if (changeRole) {
            notificationIntent.putExtra(IndexActivity.CHANGE_ROLE_KEY, true);
        }
        notificationIntent.setFlags(notificationIntent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(MainApplication.getInstance(), id,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setAutoCancel(true);
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        builder.setContentIntent(contentIntent);
        Notification notification = builder.getNotification();
        int defaults = 0;
        if (!silence) {
            defaults = defaults | Notification.DEFAULT_SOUND;
            defaults = defaults | Notification.DEFAULT_VIBRATE;
        }
        notification.defaults = defaults;
        try {
            if (!TextUtils.isEmpty(Utils.getSystemProperty("ro.miui.ui.version.name"))) {
                Field field = notification.getClass().getDeclaredField("extraNotification");
                Object extraNotification = field.get(notification);
                Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
                method.invoke(extraNotification, 0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        //用mNotificationManager的notify方法通知用户生成标题栏消息通知
        mNotificationManager.notify(id, notification);
    }

    @Override
    public void onChanged(ConnectionStatus connectionStatus) {
        switch (connectionStatus) {
            case DISCONNECTED:
                if (LoginInstance.isLogin()) {
                    RongCloudEvent.getInstance().ConnectRong(false);
                }
                break;
            case CONNECTED:
                break;
            case CONNECTING:
                break;
            case NETWORK_UNAVAILABLE:
                break;
            case KICKED_OFFLINE_BY_OTHER_CLIENT:
                break;
        }
    }

    @Override
    public boolean onReceivePushMessage(final PushNotificationMessage message) {
        LogHelper.e(TAG, "onReceivePushMessage");

        try {
            if (!LoginInstance.isLogin()) {
                return true;
            }

            final CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
            if (message.getSenderId().equals(userInfo.getUid())) {
                return true;
            }

            if (message != null) {
                String content = message.getPushContent();
                if (!TextUtils.isEmpty(content)) {
                    LogHelper.e(TAG, "content  not empty");

                    queryForInfo(MainApplication.getInstance(), message.getTargetId(), content, userInfo, true, false);
                } else {
                    LogHelper.e(TAG, " seems should not see " + String.valueOf(message.getPushContent()));
                }
            } else {
                LogHelper.e(TAG, "message.getContent() empty");
                String token = userInfo.getRongyunToken();
                LogHelper.e(TAG, "rongyun roken is : " + token);
                RongIM.connect(token, new RongIMClient.ConnectCallback() {

                    @Override
                    public void onSuccess(String userId) {
                        LogHelper.e("ron suc", "" + userId);
                        RongIMClient.getInstance().getConversation(
                                Conversation.ConversationType.DISCUSSION, message.getTargetId(), new RongIMClient.ResultCallback<Conversation>() {
                                    @Override
                                    public void onSuccess(Conversation conversation) {
                                        if (conversation != null) {
                                            LogHelper.e(TAG, "suc ");
                                            String content = getMessageContent(conversation.getLatestMessage());
                                            if (!TextUtils.isEmpty(content)) {
                                                LogHelper.e(TAG, "content  not empty");

                                                queryForInfo(MainApplication.getInstance(), message.getTargetId(), content, userInfo, true, false);
                                            } else {
                                                LogHelper.e(TAG, " seems should not see " + String.valueOf(content));
                                            }
                                        }
                                    }

                                    @Override
                                    public void onError(RongIMClient.ErrorCode errorCode) {
                                        LogHelper.e(TAG, "failed " + errorCode);
                                        if (RongIMClient.ErrorCode.IPC_DISCONNECT.equals(errorCode)
                                                || RongIMClient.ErrorCode.RC_NET_UNAVAILABLE.equals(errorCode)
                                                || RongIMClient.ErrorCode.RC_SOCKET_DISCONNECTED.equals(errorCode)) {
                                            forceConnect();
                                        }

                                    }
                                }
                        );
    /* 连接成功 */
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode e) {
                        LogHelper.e("ron failed", "");
    /* 连接失败，注意并不需要您做重连 */
                    }

                    @Override
                    public void onTokenIncorrect() {
                        LogHelper.e("ron token error", "");
    /* Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token */
                    }

                });

            }
        } catch (Exception e) {
            LogHelper.e(TAG, " error " + e.getMessage());
        }
        return true;
    }

    @Override
    public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
        return true;
    }

    @Override
    public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
        return true;
    }

    @Override
    public boolean onMessageClick(Context context, View view, Message message) {
        LogHelper.e("omg", "onMessageClick" + context.getClass().getName());
        if (message != null && message.getContent() != null) {
            if (message.getContent() instanceof LocationMessage) {
                LocationMessage locationMessage = ((LocationMessage) message.getContent());
                LogHelper.e("omg", "LocationMessage" + locationMessage.getLat() + "|" + locationMessage.getLng());
//                BillActivity.start(context);
                GaoDeMapActivity.startShow(context, locationMessage.getLat(), locationMessage.getLng(), locationMessage.getPoi());
                LogHelper.e("omg", "LocationMessage end");
                return true;
            } else if (message.getContent() instanceof ImageMessage) {
                ImageMessage imageMessage = ((ImageMessage) message.getContent());
//                Intent intent = new Intent();
//                intent.setAction(android.content.Intent.ACTION_VIEW);
//                intent.setDataAndType(imageMessage.getLocalUri(), "image/*");
//                context.startActivity(intent);
                ImageActivity.start(context, imageMessage.getRemoteUri());
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean onMessageLinkClick(Context context, String s) {
        LogHelper.e("omg", "onMessageLinkClick");
        return true;
    }

    @Override
    public boolean onMessageLongClick(Context context, View view, Message message) {
        return false;
    }

    @Override
    public Message onSend(Message message) {
        String userType = LoginInstance.getInstance().getUserInfo().isTravel() ? "1" : "2";
        MessageContent messageContent = message.getContent();
        String extra = getMessageExtra(messageContent);
        RongMessageModel rongMessageModel = new RongMessageModel();
        if (TextUtils.isEmpty(extra)) {
            rongMessageModel.setUserType(userType);
            rongMessageModel.setTimeStamp(String.valueOf(System.currentTimeMillis()));
        } else {
            rongMessageModel = JSON.parseObject(extra, RongMessageModel.class);
            rongMessageModel.increaseSendCount();
        }
        setMessageExtra(messageContent, JSONObject.toJSON(rongMessageModel).toString());
        CtUserInfo tripUserInfo = LoginInstance.getInstance().getUserInfo();
        if (tripUserInfo != null) {
            UserInfo userInfo = new UserInfo(tripUserInfo.getUid(), tripUserInfo.getNick(), Uri.parse(tripUserInfo.getHeadPic() == null ? "" : tripUserInfo.getHeadPic()));
            messageContent.setUserInfo(userInfo);
        }
        return message;
    }

    @Override
    public boolean onSent(Message message, RongIM.SentMessageErrorCode sentMessageErrorCode) {
        LogHelper.e(TAG, "onSent " + message.getSentStatus());
        if (TARGET_ID == null || !TARGET_ID.equals(message.getTargetId())) {
            return false;
        }
        MessageContent messageContent = message.getContent();
        CtUserInfo tripUserInfo = LoginInstance.getInstance().getUserInfo();
        if (tripUserInfo != null) {
            UserInfo userInfo = new UserInfo(tripUserInfo.getUid(), tripUserInfo.getNick(), Uri.parse(tripUserInfo.getHeadPic() == null ? "" : tripUserInfo.getHeadPic()));
            messageContent.setUserInfo(userInfo);
        }
        String extra = getMessageExtra(messageContent);
        RongMessageModel rongMessageModel = null;
        if (!TextUtils.isEmpty(extra)) {
            rongMessageModel = JSON.parseObject(extra, RongMessageModel.class);
        }
        if (Message.SentStatus.SENT.equals(message.getSentStatus())) {
            if (rongMessageModel != null) {
                rongMessageModel.setIsSuccess(true);
            }
        } else {
            if (rongMessageModel != null) {
                rongMessageModel.setIsSuccess(false);
            }
        }
        LogHelper.e(TAG, message.getTargetId());

        if (RongIM.SentMessageErrorCode.UNKNOWN.equals(sentMessageErrorCode)
                ) {
            forceConnect();
        }
        if (sentMessageErrorCode == null) {
            mErrorCode = null;
        }

        Pair<Integer, String> content = getMessageLoadToService(message.getContent());
        if (content != null) {
            ApiProxy putDialogProxy = new ApiProxy(new IProxyCallback() {
                @Override
                public boolean onProxyResult(ProxyResult<?> result) {
                    return false;
                }
            });
            putDialogProxy.setShouldResponseOnUiThread(false);
            MessageBusiness.putDialog(putDialogProxy, ORDER_ID, RECEIVER_ID, USER_ID,
                    content.first, content.second, SERVICE_ID, rongMessageModel, mErrorCode);

            LogHelper.e(TAG,
                    TextUtils.join("|",
                            new String[]{" send", ORDER_ID, RECEIVER_ID, USER_ID, SERVICE_ID, TARGET_ID,
                                    content.second.toString()}
                    ));
        }


        return false;
    }

    @Override
    public boolean handleMessage(android.os.Message msg) {
        return false;
    }

    @Override
    public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String s) {
        return false;
    }

    @Override
    public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String s) {
        return false;
    }

    @Override
    public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) {
        return false;
    }

    @Override
    public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
        return false;
    }

    @Override
    public Group getGroupInfo(String s) {
        return null;
    }

    @Override
    public void onStartLocation(Context context, LocationCallback locationCallback) {

    }

    @Override
    public void onComplete(AbstractHttpRequest abstractHttpRequest, Object o) {

    }

    @Override
    public void onFailure(AbstractHttpRequest abstractHttpRequest, BaseException e) {

    }

    @Override
    public GroupUserInfo getGroupUserInfo(String s, String s1) {
        return new GroupUserInfo("CCC", "XXX", "EEE");
    }
}
